package com.huiruan.controller.pc.sys;

import com.huiruan.entity.FileInfo;
import com.huiruan.service.FileStorageService;
import com.huiruan.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/files")
@Tag(name = "文件处理接口", description = "提供文件上传、下载、管理等操作")
public class FileHandlerController {

    private final FileStorageService fileStorageService;

    @Autowired
    public FileHandlerController(FileStorageService fileStorageService) {
        this.fileStorageService = fileStorageService;
    }

    @PostMapping("/upload")
    @Operation(summary = "上传单个文件", description = "上传一个文件到服务器")
    public Result<FileInfo> uploadFile(@RequestParam("file") MultipartFile file) {

        FileInfo fileInfo = fileStorageService.storeFile(file);

        String fileDownloadUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/files/download/")
                .path(fileInfo.getFilename())
                .toUriString();

        fileInfo.setFileUrl(fileDownloadUrl);
        return Result.success(fileInfo);
    }


    @PostMapping("/upload-multiple")
    @Operation(summary = "上传多个文件", description = "一次上传多个文件到服务器")
    public Result<List<FileInfo>> uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) {
        List<FileInfo> fileInfos = Arrays.stream(files)
                .map(file -> {
                    FileInfo fileInfo = fileStorageService.storeFile(file);

                    String fileDownloadUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                            .path("/files/download/")
                            .path(fileInfo.getFilename())
                            .toUriString();

                    fileInfo.setFileUrl(fileDownloadUrl);
                    return fileInfo;
                })
                .collect(Collectors.toList());

        return Result.success(fileInfos);
    }

    @GetMapping("/download/{filename:.+}")
    @Operation(summary = "下载文件", description = "根据文件名下载文件")
    public ResponseEntity<Resource> downloadFile(
            @PathVariable String filename,
            HttpServletRequest request) {

        Resource resource = fileStorageService.loadFileAsResource(filename);

        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            // 无法确定文件类型，使用默认值
        }

        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

    @GetMapping("/list")
    @Operation(summary = "获取文件列表", description = "获取服务器上存储的所有文件信息")
    public List<FileInfo> listFiles() {
        return fileStorageService.loadAllFiles();
    }

    @DeleteMapping("/{filename}")
    @Operation(summary = "删除文件", description = "根据文件名删除服务器上的文件")
    public ResponseEntity<?> deleteFile(
            @PathVariable String filename) {

        fileStorageService.deleteFile(filename);
        return ResponseEntity.ok().body("文件删除成功: " + filename);
    }

    @DeleteMapping("/")
    @Operation(summary = "删除所有文件", description = "删除服务器上存储的所有文件")
    public ResponseEntity<?> deleteAllFiles() {
        fileStorageService.deleteAllFiles();
        return ResponseEntity.ok().body("所有文件已成功删除");
    }
}
